package com.wjb.xietong.ota;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import android.view.ContextThemeWrapper;
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.wjb.xietong.R;
import com.wjb.xietong.W3.HttpUtil;
import com.wjb.xietong.control.AsyncImageLoader;
import com.wjb.xietong.ota.task.OTATaskDetail;
import com.wjb.xietong.server.Msg;
import com.wjb.xietong.server.MsgNotify;
import com.wjb.xietong.server.crm.CrmService;
import com.wjb.xietong.server.crm.SalesInfo.SalesData;
import com.wjb.xietong.server.crm.SellerInfo.Seller;

public class TabCrm extends BaseFM{
	
	private static final String [] eshopName ={""};  
	private Spinner spinner = null;  
	private ArrayAdapter<String> adapter = null;  
	private Button btToday = null;
	private Button btYestoday = null;
	private LayoutInflater mInflater = null;
	
	private Seller sellerShow = null;
	private boolean bToday = true;
	
    private AnimationDrawable anim;
	private ImageSwitcher imageSwitcher;

	private AnimationDrawable anim2;
	private ImageSwitcher imageSwitcher2;
	
	private int lastY = 0;
	private ScrollView sv;
	
	private LinearLayout llRefreshGp = null;
	private LinearLayout llUntilTmGp = null;
	
	private TextView btShopName = null;
	
	private boolean bRefreshing = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = super.onCreateView(inflater, container, savedInstanceState);
		setContentField(inflater.inflate(R.layout.crm_tab, null));
		
		setTopBarAndAction(getString(R.string.STR_TAB_CRM), null, new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
			}
		});
		
		hideTitleBar();

		
		spinner = (Spinner)view.findViewById(R.id.spinner);  
		adapter = new ArrayAdapter<String>(getActivity(), R.layout.crm_spinner_style, eshopName);  
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
        spinner.setAdapter(adapter);  
        //spinner.setVisibility(View.VISIBLE);
        spinner.setPrompt(this.getString(R.string.crm_choose_shop));
        
        spinner.setOnItemSelectedListener(new OnItemSelectedListener(){  
            @Override
            public void  onItemSelected(AdapterView<?> arg0, View arg1,
                  int arg2, long arg3) {

            	int w = arg1.getWidth();
            	int w2 = spinner.getWidth();
            	
        		LayoutParams params = spinner.getLayoutParams();  
        	   
        		//spinner.per
//        		if (arg1.getWidth() > 0){
//	        	    params.width = arg1.getWidth() + 20;
//	        	    spinner.setLayoutParams(params); 
//        		}
            	
//            	sellerShow = CrmService.getInstance().getSeller(arg2);
//            	if (sellerShow != null){
//            		CrmService.getInstance().requestSellerCrm(sellerShow, getToday());
//            		startLoadingIcon();
//            		
//            		btShopName.setText(String.format("[%s]%s",sellerShow.getTypeString(), sellerShow.nick));
//            	}
            }

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
        });
        
        
        
        
        TextView cur = (TextView) view.findViewById(R.id.idCurTime);
        cur.setText(getCurTime());
        btToday = (Button)view.findViewById(R.id.btToday);
        btYestoday = (Button)view.findViewById(R.id.btYestoday);
        btToday.setOnClickListener(new Button.OnClickListener(){
            @SuppressWarnings("deprecation")
			public void onClick(View v) {    
            	Drawable draw = getResources().getDrawable(R.drawable.crm_today_background_press);  
            	v.setBackgroundDrawable(draw);
            	btToday.setTextColor(getResources().getColor(R.color.crm_bt_press));
            	
            	draw = getResources().getDrawable(R.drawable.crm_yesterday_background);
            	btYestoday.setBackgroundDrawable(draw);
            	btYestoday.setTextColor(getResources().getColor(R.color.crm_bt_normal));
            	
            	if (sellerShow != null){
            		CrmService.getInstance().requestSellerCrm(sellerShow, getToday());
            	}
            	bToday = true;
            	
            	llUntilTmGp.setVisibility(View.VISIBLE);
            	startLoadingIcon();
            }    
        });
        btYestoday.setOnClickListener(new Button.OnClickListener(){
            @SuppressWarnings("deprecation")
			public void onClick(View v) {    
            	Drawable draw = getResources().getDrawable(R.drawable.crm_yesterday_background_press);  
            	v.setBackgroundDrawable(draw);
            	
            	draw = getResources().getDrawable(R.drawable.crm_today_background);
            	btToday.setBackgroundDrawable(draw);
            	
            	btToday.setTextColor(getResources().getColor(R.color.crm_bt_normal));
            	btYestoday.setTextColor(getResources().getColor(R.color.crm_bt_press));
            
            	if (sellerShow != null){
            		CrmService.getInstance().requestSellerCrm(sellerShow, getYesterday());
            	}
            	bToday = false;
            	
            	llUntilTmGp.setVisibility(View.INVISIBLE);
            	
            	startLoadingIcon();
            }
  
        });    

        btShopName = (TextView)view.findViewById(R.id.idShopname);
        btShopName.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {    
				showShopList();

			}
        });
        
        ImageView ivArrowDown = (ImageView)view.findViewById(R.id.idArrowDown);
        ivArrowDown.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {    
				showShopList();
			}
        });
        
        mInflater = inflater;
       
        
        
        sv = (ScrollView) view.findViewById(R.id.idScrollView);
        sv.setOnTouchListener(svTouchEvent);

    	imageSwitcher = (ImageSwitcher)view.findViewById(R.id.image_switcher);
		anim = (AnimationDrawable)imageSwitcher.getBackground();
		
		imageSwitcher2 = (ImageSwitcher)view.findViewById(R.id.image_switcher2);
		anim2 = (AnimationDrawable)imageSwitcher.getBackground();
		llRefreshGp = (LinearLayout) view.findViewById(R.id.idRefreshGp);
		
		llUntilTmGp = (LinearLayout) view.findViewById(R.id.idUntilGroup);
		
		startLoadingIcon();
		
		lastY = 0;
		
		CrmService.getInstance().setNotify(new CRMMsgNotify());
        
		if (sellerShow != null){
        	this.showSeller(view);
        	this.showStatis(view);
        	this.showTopSales(view);
        }
        CrmService.getInstance().requestSeller();
        
		return view;
	}
	
	
	private void showShopList(){
		
		LinkedList<Seller> list = CrmService.getInstance().getSeller();
		
		String[] nameList = new String[list.size()];
		Iterator<Seller> it = list.iterator();
		int index = 0;
		while (it.hasNext()){
			Seller sl = it.next();
			
			nameList[index] = String.format("[%s]%s",sl.getTypeString(), sl.nick);
			index++;
		}
		
		new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialogCustom)).setTitle("请选择店铺").setItems(nameList,new DialogInterface.OnClickListener(){  
			public void onClick(DialogInterface dialog, int which){  
   
				sellerShow = CrmService.getInstance().getSeller(which);
				if (sellerShow != null){
					String date = null;
	    			if (bToday){
	    				date = getToday();
	    			}
	    			else{
	    				date = getYesterday();
	    			}
					CrmService.getInstance().requestSellerCrm(sellerShow, date);
					startLoadingIcon();
		
					btShopName.setText(String.format("[%s]%s",sellerShow.getTypeString(), sellerShow.nick));
				}
				dialog.dismiss();  
			}  
		}).show();
		 
	}
	View.OnTouchListener svTouchEvent = new View.OnTouchListener(){

		@Override
		public boolean onTouch(View v, MotionEvent e) {
			int action = e.getAction();
	        int y= (int) e.getRawY();
	        switch (action) {
	        case MotionEvent.ACTION_DOWN:
	            lastY = y;
	            break;
	 
	        case MotionEvent.ACTION_MOVE:
	        	if (lastY == 0){
	        		lastY = y;
	        	}
	        		
	            int m = y - lastY;     
	            if(m > 32){
	            	if (sv.getScrollY() == 0){
	            		if (bRefreshing == false){
		            		String date = null;
			    			if (bToday){
			    				date = getToday();
			    			}
			    			else{
			    				date = getYesterday();
			    			}
			        		CrmService.getInstance().requestSellerCrm(sellerShow, date);
			        		//startLoadingIcon();
			        		startRefresh();
			        		bRefreshing = true;
	            		}
	            	}
	
	             }
	            lastY = y;
	            break;
	        case MotionEvent.ACTION_UP:
	             
	            break;
	             
	        case MotionEvent.ACTION_CANCEL:
	             
	            break;
	        }
	        sv.onTouchEvent(e);
	        return true;
		}
	};
	
	@Override
	protected void findView(View v) {

	}
	
	private void startRefresh(){
		llRefreshGp.setVisibility(View.VISIBLE);
		imageSwitcher2.setVisibility(View.VISIBLE);
		anim2.start();
	}
	
	private void stopRefresh(){
		llRefreshGp.setVisibility(View.GONE);
		imageSwitcher2.setVisibility(View.GONE);
		anim2.stop();
	}
	
	private void startLoadingIcon(){
		imageSwitcher.setVisibility(View.VISIBLE);
		anim.start();
	}
	private void stopLoadingIcon(){
		imageSwitcher.setVisibility(View.INVISIBLE);
		anim.stop();
		
		stopRefresh();
	}
	
	private int showTopSales(View v){
		
		if (v == null){
			return -1;
		}
		mInflater = (LayoutInflater)v.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		TableLayout tableLayout = (TableLayout)v.findViewById(R.id.layout_top10);
		
		
		@SuppressWarnings("deprecation")
		TableLayout.LayoutParams tableRowParams=
				  new TableLayout.LayoutParams
				  (TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.FILL_PARENT);
		tableRowParams.setMargins(0, 0, 0, 10);
		
		int j = tableLayout.getChildCount();
		for(int i = j; i >= 0; i--){
			tableLayout.removeView(tableLayout.getChildAt(i));
		}
		
		Iterator<SalesData> it = sellerShow.listSales.iterator();
		while (it.hasNext()){
			SalesData sd = it.next();
			
			View vInfo = mInflater.inflate(R.layout.crm_goods_info,
					null);
			
			TextView txt_v = (TextView)vInfo.findViewById(R.id.txt_name);
			txt_v.setText(sd.itemName);
			txt_v.setTag(sd);
			txt_v.setOnClickListener(salesViewLS);
			
			txt_v = (TextView)vInfo.findViewById(R.id.txt_sold_num);
			txt_v.setText(String.format(this.getString(R.string.crm_sold_num_fmt), sd.tradeNum));
			
			txt_v = (TextView)vInfo.findViewById(R.id.txt_price);
			txt_v.setText(String.format(this.getString(R.string.crm_sold_price_fmt), sd.price));
			
			txt_v = (TextView)vInfo.findViewById(R.id.txt_total);
			txt_v.setText(String.format(this.getString(R.string.crm_sold_total_fmt), sd.tradePayment));
			
			
			ImageView iv = (ImageView)vInfo.findViewById(R.id.img_goods);
			iv.setTag(sd);
			setSalesImgSize(iv);
			iv.setOnClickListener(salesViewLS);
			//HttpUtil.getImage(sd.imageURL, iv, 0, 0);
			String url = adjustUrl(iv, sd.imageURL);
			AsyncImageLoader.Instance().loadForImageView(url, iv, 0);
			
			
			
			TableRow tableRow = new TableRow(v.getContext());
			tableRow.addView(vInfo);  
			tableRow.setLayoutParams(tableRowParams);
			tableLayout.addView(tableRow);
		}
		
		TextView cur = (TextView) v.findViewById(R.id.idCurTime);
        cur.setText(getCurTime());
        

		return 0;
	}
	
	View.OnClickListener salesViewLS = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			SalesData sd = (SalesData) v.getTag();
			openUrl(sd.itemID);
		}
	};
	
	private void openUrl(long itemID){
		String url = String.format(this.getString(R.string.crm_sales_url_fmt), itemID);
//		Intent intent = new Intent(Intent.ACTION_VIEW);
//		intent.setData(Uri.parse(url));
//		startActivity(intent);
		
		Intent intent = new Intent(getActivity(), CrmSalesDetail.class);
		intent.putExtra("url", url);
		startActivity(intent);
	}
	private int showSeller(View v){
		
		if (v == null){
			return -1;
		}
		
		LinkedList<Seller> list = CrmService.getInstance().getSeller();
			
		List<String> nameList = new ArrayList<String>();
		Iterator<Seller> it = list.iterator();
		while (it.hasNext()){
			Seller sl = it.next();
			
			nameList.add(String.format("[%s]%s",sl.getTypeString(), sl.nick));
			
			if (sellerShow == null){
				sellerShow = sl;
				
			}
			
		}
		
		if (sellerShow != null){
			btShopName.setText(String.format("[%s]%s",sellerShow.getTypeString(), sellerShow.nick));
		}
		
		ArrayAdapter<String> ad = new ArrayAdapter<String>(getActivity(),
				 R.layout.crm_spinner_style, nameList);
		
		ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
		spinner.setAdapter(ad);
		

		
		return 0;
	}
	
	private int showStatis(View v){
		
		if (v == null){
			return -1;
		}
		
		TextView txt = (TextView) v.findViewById(R.id.idPayment);
		txt.setText(String.format("%.1f", sellerShow.sellerStatis.paid));
		
		txt = (TextView) v.findViewById(R.id.idWaitPay);
		txt.setText(String.format("%.1f", sellerShow.sellerStatis.waitToPay));
		
		txt = (TextView) v.findViewById(R.id.idOrders);
		txt.setText(String.format("%d", sellerShow.sellerStatis.paidTrade));
		
		txt = (TextView) v.findViewById(R.id.idWaitOrders);
		txt.setText(String.format("%d", sellerShow.sellerStatis.waitToPaidTrade));
		
		txt = (TextView) v.findViewById(R.id.idBuyers);
		txt.setText(String.format("%d", sellerShow.sellerStatis.buyerAll));
		
		txt = (TextView) v.findViewById(R.id.idOldBuyers);
		txt.setText(String.format("%d", sellerShow.sellerStatis.buyerOld));
		
		txt = (TextView) v.findViewById(R.id.idNewBuyers);
		txt.setText(String.format("%d", sellerShow.sellerStatis.buyerNew));
		

		return 0;
	}
	
	
    
	@SuppressLint("SimpleDateFormat")
	private String getToday(){
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");  
		Date d=new Date();
		return sDateFormat.format(new java.util.Date(d.getTime()));  
	}
	
	@SuppressLint("SimpleDateFormat")
	private String getYesterday(){
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");  
		Date d=new Date();
		return sDateFormat.format(new java.util.Date(d.getTime() - 1 * 24 * 60 * 60 * 1000));  
	}
	
	@SuppressLint("SimpleDateFormat")
	private String getCurTime(){
		SimpleDateFormat sDateFormat = new SimpleDateFormat("HH:mm");  
		Date d=new Date();
		return sDateFormat.format(new java.util.Date(d.getTime()));  
	}
	
	@SuppressLint("HandlerLeak")
	Handler msgHandler = new Handler() {   
        public void handleMessage(Message msg) {    
             switch (msg.what) {    
                  case Msg.TYPE_CRM_SELLER:    
                	  showSeller(getView());
              		  if (sellerShow != null){
            			  CrmService.getInstance().requestSellerCrm(sellerShow, getToday());
            		  }
            		  else{
            			  stopLoadingIcon();
            		  }
                      break; 
                  case Msg.TYPE_CRM_SELLER_STATIS:
                	  showStatis(getView());
                	  bRefreshing = false;
              		  if (sellerShow != null){
            			  String date = null;
            			  if (bToday){
            				  date = getToday();
            			  }
            		  	  else{
            				  date = getYesterday();
            			  }
                		  CrmService.getInstance().requestTopSales(sellerShow, date);
                	  }
                	  break;
                  case Msg.TYPE_CRM_SALES:
                	  showTopSales(getView());
                      stopLoadingIcon();
                	  break;
             }    
             if (msg.arg1 != Msg.MSG_SUCCESS){
            	 String str = new String(msg.getData().getString("msg"));
            	 Toast.makeText(getApplicationContext(),
            			 str == null ? "服务器同步数据失败" : str,
							Toast.LENGTH_LONG).show();
             }
        }    
    };   
    
	private class CRMMsgNotify implements MsgNotify {

		public CRMMsgNotify(){
			
		}
		@Override
		public int message(Msg msg) {
			
			Message message = new Message();
			message.what = msg.type;    
			message.arg1 = msg.msg;
			if (msg.msg != Msg.MSG_SUCCESS && msg.str != null)
			{
				Bundle bundle = new Bundle();    
				bundle.putString("msg", msg.str);
				message.setData(bundle);
			}
			
			msgHandler.sendMessage(message);
			return 0;
		}
		
	}
	
	private String adjustUrl(ImageView iv, String url){
		LayoutParams para;
        para = iv.getLayoutParams();
        
        int pos = 0;
        int index = url.length();
        index--;
        while (index > 0){
        	if (url.getBytes()[index] == '.'){
        		pos = index;
        		break;
        	}
        	index--;
        }
        int width = 140;//(int)(((Math.ceil(((double)para.width) / 10)) + 1) * 10);
        int height = 140;//(int)(((Math.ceil(((double)para.height) / 10)) + 1) * 10);
        
        if (pos > 0){
        	return String.format("%s_%dx%d%s", url, 
        			width, height, url.substring(pos, url.length()));
        }
        else{
        	return url;
        }
	}
	
	private int setSalesImgSize(ImageView iv){
//		Display mDisplay = this.getActivity().getWindowManager().getDefaultDisplay();
//		int W = mDisplay.getWidth();
//		int H = mDisplay.getHeight();
//		
//		LayoutParams params = iv.getLayoutParams();  
//	    
//		
//	    params.width = W / 4;  
//	    params.height = params.width;  
//	    iv.setLayoutParams(params);  
		return 0;
	}

	protected Context getApplicationContext() {
		return this.getView().getContext();
	}
}
